<template>
  <div class="registration">
    <nav-bar :title="$route.meta.title">
      <van-icon :color="variables.black" size="18" />
    </nav-bar>

    <van-form
      class="form"
      validate-trigger="onSubmit"
      :show-error="false"
      auto-complate="off"
      @submit="onSubmit"
    >
      <van-field
        v-model="form.inviteCode"
        type="text"
        required
        clearable
        name="邀请码"
        label="邀请码"
        placeholder="邀请码"
        :rules="[
          {
            required: true,
            message: '邀请码',
          },
        ]"
      />

      <van-field
        v-model="form.realName"
        type="text"
        required
        clearable
        :formatter="verifyName"
        name="真实姓名"
        label="真实姓名"
        :rules="[{ required: true, message: '请输入真实姓名!' }]"
      />

      <van-field
        v-model="form.password"
        type="password"
        required
        clearable
        auto-complate="off"
        name="设置密码"
        label="设置密码"
        placeholder="请设置密码"
        :rules="[{ required: true, message: '请设置密码!' }]"
      />

      <van-field
        v-model="form.confirmPassword"
        type="password"
        required
        auto-complate="off"
        clearable
        name="确认密码"
        label="确认密码"
        placeholder="请再次输入密码确认"
        :rules="[{ required: true, message: '请再次输入密码确认!' }]"
      />
      <!-- <div style="display: flex; "> 
        style="width: 70%;"-->
        <van-field
          v-model="form.mobile"
          
          type="text"
          required
          clearable
          name="手机号码"
          label="手机号码"
          placeholder="请输入手机号码"
          :rules="[
            {
              validator: checkPhone,
              required: true,
              message: '请输入正确的手机号码!',
            },
          ]"
        />
        <!-- <van-button native-type="button" @click.stop="sendSms">{{ btnText }}</van-button> -->
      <!-- </div> -->
      <!-- <div style="display: flex; ">
        <van-field
          v-model="form.mobileCode"
          type="text"
          required
          clearable
          name="验证码"
          label="手机验证码"
          placeholder="请输入手机验证码"
          :rules="[
            {
              validator: checkCode,
              required: true,
              message: '请输入正确的手机验证码!',
            },
          ]"
        />
      </div> -->
      <van-field
        v-model="form.captchaCode"
        type="text"
        required
        center
        clearable
        name="图形验证码"
        maxlength="4"
        label="图形验证码"
        placeholder="请输入图形验证码"
        :rules="[{ required: true, message: '请输入正确的图形验证码！' }]"
      >
        <template #button>
          <div class="regist-code">
            <!-- <img :src="captchaImg" @click="getCaptcha"> -->
             <canvas ref="canvas" height="40px" @click="getCaptcha"></canvas>
          </div>
        </template>
      </van-field>
        <!-- <dragVerify
              @success="handleSuccess"
              v-model="isVerifySuccess"
            ></dragVerify> -->
      <div style="margin: 36px">
        <van-button
          round
          block
          :loading="loading"
          type="info"
          loading-text="注册中..."
          native-type="submit"
        >注册</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>

import dragVerify from '@/components/dragVerify/dragVerify.vue'
import variables from '@/styles/variables.scss'
import { getCaptcha, getMailCode } from '@/api/login'
import { setRegistry } from '@/api/user'

export default {
  name: 'Regist',
  components:{
    dragVerify
  },
  data() {
    return {
      form: {
        mobile: '',
        email: '',
        password: '',
        confirmPassword: '',
        realName: '',
        peopleNum: '',
        emailCode: '',
        emailKey: '',
        captchaCode: '',
        captchaKey: '',
        mobileCode: ''
      },
      isVerifySuccess:false,
      disabled: false,
      totalCount: 60,
      loading: false,
      captchaImg: '',
      sets: ''
    }
  },
  computed: {
    variables() {
      return variables
    },
    btnText() {
      return this.totalCount !== 60
        ? `${this.totalCount}秒后获取`
        : '获取验证码'
    }
  },
  created() {
    // this.$toast.loading({message:'加载中',duration:10000})
    this.form.inviteCode = this.$route.query.inviteCode
    this.getCaptcha()
  },
  mounted() {
    // this.getCaptcha()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      // 通过 `vm` 访问组件实例
      // 在这里进行数据请求
      // vm.getCaptcha();
    });
  },
  methods: {
    // 滑块验证成功回调
    handleSuccessFun() {
      this.isVerifySuccess  = true
    },
    // 滑块验证失败回调
    handleErrorFun() {},
    handleSuccess(success) {
      this.isVerifySuccess = success; // 更新滑块验证状态
    },
    verifyName(val){
      if(val.indexOf('<')!=-1 || val.indexOf('>')!=-1){
        val = ''
        this.$toast.fail('包含非法字符')
      }
      return val
    },
    // 获取图形验证码
    getCaptcha() {
      getCaptcha().then((res) => {
        // let ar = res.map.captchaImg.split(',')
        // if(ar.length==1){
        //   this.getCaptcha()
        // }
        if(res.map.captchaImg){
          this.$toast.clear()
        }else{
         return this.getCaptcha()
        }
        const text = res.map.captchaImg
        const canvas = this.$refs.canvas;
        const ctx = canvas.getContext('2d');
        // const text = this.generateRandomCode(4); // 生成4位验证码
  
        canvas.width = 100;
        canvas.height = 40;
        ctx.fillStyle = '#f9f9f9';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.font = '20px Arial';
        ctx.fillStyle = '#000';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(text, canvas.width / 2, canvas.height / 2);
        // this.form.captchaKey = res.map.captchaKey
        this.$set(this.form,'captchaKey',res.map.captchaKey)
      })
    },
    sendSms() {
      this.sets = setInterval(() => {
        if (this.totalCount > 1) { this.totalCount-- } else {
          this.totalCount = 60
          clearInterval(this.sets)
        }
      }, 1000)
    },
    // 获取邮箱验证码
    getMailCode() {
      const { email } = this.form
      if (!email || !this.checkEmail(email)) {
        this.$toast.fail('请先输入正确的邮箱地址')
        return
      }
      const captchaKey = this.form.captchaKey
      const captchaCode = this.form.captchaCode
      const mobile = this.form.mobile
      getMailCode({ email, captchaKey, captchaCode, mobile }).then((res) => {
        this.form.emailKey = res.map.emailKey
        this.disabled = true
        this.totalCount = 60
        this.interval = setInterval(() => {
          this.totalCount--
          if (this.totalCount === 0) {
            clearInterval(this.interval)
            this.disabled = false
          }
        }, 1000)
        this.$notify({
          type: 'success',
          message: '邮箱验证码已发送',
          duration: 2000
        })
      })
    },
    // 校检邮箱
    checkEmail(email) {
      const reg =
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      return reg.test(email)
    },
    // 校检手机号
    checkPhone(num) {
      if (num === 123456789) return true
      const reg = /^[1][3,4,5,7,8,2,6,9][0-9]{9}$/
      if (reg.test(num)) {
        return true
      }
      return false
    },
    checkCode(code) {
      if (code.length !== 6) {
        return false
      }
      return true
    },
    // 提交
    onSubmit() {
      const { password, confirmPassword } = this.form
      if (password !== confirmPassword) {
        this.$toast.fail('确认密码与设置的不一致')
        return
      }
      this.loading = true
      setRegistry(this.form)
        .then((res) => {
          this.$notify({
            type: 'success',
            message: '注册成功，请登录',
            duration: 2000,
            onOpened: () => {
              this.$router.push('/login')
            }
          })
        }).catch(err => {
          console.log(err.toString())
          const error = err.toString()
          if (error.includes('手机号已注册，请更换手机号')) {
            setTimeout(()=>{
              this.$router.push('/login')
            },1000)
          }
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.form {
  padding: 24px;
}
.regist-code {
  // height: 40px;
  img {
    vertical-align: middle;
    position: relative;
    top: -2.467vw;
  }
}
</style>
